const handleBlogRouter = require('./src/router/blog.js')
const handleUserRouter = require('./src/router/user.js')
const querystring = require('querystring')

const getPostData = (req) => {
  return new Promise((resolve, reject) => {
    if (req.method !== 'POST') {
      resolve({})
      return
    }
    if (req.headers['content-type'] !== 'application/json') {
      resolve({})
    }
    let postData = ''
    req.on('data', chunk => {
      postData += chunk.toString()
    })
    req.on('end', () => {
      if (!postData) {
        resolve({})
        return
      }
      resolve(
        JSON.parse(postData)
      )
    })
  })
}
// 创建监听的回调
const serverHandler = (req, res) => {
  // 设置返回格式头JSON
  res.setHeader('Content-type', 'application/json')
  const url = req.url
  // 解析query
  req.query = querystring.parse(url.split('?')[1])
  getPostData(req).then((postData) => {
    req.body = postData
    const blogResult = handleBlogRouter(req, res)
    if (blogResult) {
      blogResult.then(blogData => {
        if (blogData) {
          res.end(JSON.stringify(blogData))
          return
        }
      })
      return
    }
    // if (blogData) {
    //   res.end(JSON.stringify(blogData))
    //   return
    // }
    const userDataResult = handleUserRouter(req, res)
    if (userDataResult) {
      userDataResult.then((userData) => {
        if (userData) {
          res.end(JSON.stringify(userData))
          return
        }
      })
      return
    }
    // if (userData) {
    //   res.end(JSON.stringify(userData))
    //   return
    // }
    res.writeHead(404, {
      'Content-type': 'application/plain'
    })
    res.write("404 Not Found\n")
    res.end()
  })
}
module.exports = serverHandler